
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  control;

import java.io.*;
import java.net.*;
import java.util.*;

import logger.PoolLogger;
import sms.SmsBuffer;
import utility.Index;

public class ClientWatch extends Thread
{
	PoolLogger pl;
	public ClientWatch() {
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	public void run()
	{	
		int port = 9999;
		try
		{
			ServerSocket server = new ServerSocket(port,5);
			System.out.println("control::ClientWatch::run()::Listening for connections on port "+server.getLocalPort());
			pl.info("control::ClientWatch::run()::Listening for connections on port "+server.getLocalPort());
			pl.debug("control::ClientWatch::run()::Listening for connections on port "+server.getLocalPort());
			pl.warn("control::ClientWatch::run()::Listening for connections on port "+server.getLocalPort());
			pl.fatal("control::ClientWatch::run()::Listening for connections on port "+server.getLocalPort());
			pl.error("control::ClientWatch::run()::Listening for connections on port "+server.getLocalPort());
			pl.trace("control::ClientWatch::run()::Listening for connections on port "+server.getLocalPort());
			
			while(true)
			{
				Socket connection = server.accept();
				if(connection !=null)
				{
					System.out.println(connection.getInetAddress().getHostName());
					pl.info(connection.getInetAddress().getHostName());
					pl.debug(connection.getInetAddress().getHostName());
					pl.warn(connection.getInetAddress().getHostName());
					pl.fatal(connection.getInetAddress().getHostName());
					pl.error(connection.getInetAddress().getHostName());
					pl.trace(connection.getInetAddress().getHostName());					
				}
				try
				{
					System.out.println("control::ClientWatch::run()::Connection established with "+connection);
					pl.info("control::ClientWatch::run()::Connection established with "+connection);
					pl.debug("control::ClientWatch::run()::Connection established with "+connection);
					pl.warn("control::ClientWatch::run()::Connection established with "+connection);
					pl.fatal("control::ClientWatch::run()::Connection established with "+connection);
					pl.error("control::ClientWatch::run()::Connection established with "+connection);
					pl.trace("control::ClientWatch::run()::Connection established with "+connection);
					ClientProcess input = new ClientProcess(connection);
					input.start();
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}
}

class ClientProcess extends Thread
{	
	Socket connection;
	
	PoolLogger pl;
	
	public ClientProcess(Socket connection)
	{		 
		try
		{
			this.connection = connection;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	@SuppressWarnings("unchecked")
	public void run()
	{
		try
		{
			String Username=null;
			String request=null;						 
			
			BufferedReader IncomingRequest = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			
			Username =  IncomingRequest.readLine();
			request  = IncomingRequest.readLine();
			if(Index.indexOf(request, "#")==-1)
			{
				SendResponse sendresponse = new SendResponse(connection,"password not present",Username,request);
				sendresponse.start();
			}
			System.out.println("\ncontrol::ClientProcess::run()::Client user name is -->"+Username);
			pl.debug("\ncontrol::ClientProcess::run()::Client user name is -->"+Username);
			pl.warn("\ncontrol::ClientProcess::run()::Client user name is -->"+Username);
			pl.fatal("\ncontrol::ClientProcess::run()::Client user name is -->"+Username);
			pl.error("\ncontrol::ClientProcess::run()::Client user name is -->"+Username);
			pl.trace("\ncontrol::ClientProcess::run()::Client user name is -->"+Username);
			
			System.out.println("\ncontrol::ClientProcess::run()::Incoming Request is-->"+request);
			pl.debug("\ncontrol::ClientProcess::run()::Incoming Request is-->"+request);
			pl.warn("\ncontrol::ClientProcess::run()::Incoming Request is-->"+request);
			pl.fatal("\ncontrol::ClientProcess::run()::Incoming Request is-->"+request);
			pl.error("\ncontrol::ClientProcess::run()::Incoming Request is-->"+request);
			pl.trace("\ncontrol::ClientProcess::run()::Incoming Request is-->"+request);
					
			if(Username.startsWith("TO:")==false)
			{
				SmsControl control = new SmsControl(Username, request);
				StringBuffer response=new StringBuffer();
				Vector<Object> messageVector = new Vector<Object>();
				messageVector=control.splitRequest();
				
				for(Object object : messageVector)
				{
					Hashtable<Object,Object> h1 = (Hashtable<Object, Object>)object;
					response.append(h1);
				}
				/*h1 = control.messageProcessing();
				
				
				if(h1.containsKey("ErrorUser")==false)
				{
					h2 = control.requestProcess();
					response.append(h2);
					h1.clear();
					h2.clear();
				}
				else
				{
					System.out.println("Unable to Find user");
					h1.put("ErrorUser", "Unable to Find user or password");
					database.pLog.Logger.append("Error User :: Unable to Find user or password");
					response.append(h1);
				}*/
				char[] strCs = response.toString().toCharArray();
				response = new StringBuffer();
				for(int i=0;i<strCs.length;i++)
				{
					if(strCs[i]=='{'||strCs[i]=='}')
					{
						response.append(' ');
					}
					else
						response.append(strCs[i]);
				}
				response = new StringBuffer(response.toString().replace("\t", " "));
				response = new StringBuffer(response.toString().replace("\n", " "));
				SendResponse sendresponse = new SendResponse(connection,response.toString(),Username,request);
				sendresponse.start();
			}
			else
			{
				Username = Username.substring(Username.indexOf(':'));
				System.out.println("control::ClientProcess::run()::Message Delivery Report for user "+Username);
				pl.debug("control::ClientProcess::run()::Message Delivery Report for user "+Username);
				pl.warn("control::ClientProcess::run()::Message Delivery Report for user "+Username);
				pl.fatal("control::ClientProcess::run()::Message Delivery Report for user "+Username);
				pl.error("control::ClientProcess::run()::Message Delivery Report for user "+Username);
				pl.trace("control::ClientProcess::run()::Message Delivery Report for user "+Username);				
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}

class SendResponse extends Thread
{
	PrintStream outputResponse;
	Socket connection;
	String response;
	String Username;
	PoolLogger pl;
	
	public SendResponse(Socket connection,String response,String Username,String request)
	{
		try
		{
			this.connection = connection;
			this.response = request + " :: REPLY :: "+response;
			this.Username = Username;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	public void run()
	{
		try
		{
			outputResponse= new PrintStream(connection.getOutputStream());
			System.out.println(connection);
			pl.debug(connection);
			pl.warn(connection);
			pl.fatal(connection);
			pl.error(connection);
			pl.trace(connection);
			
			//out.write("I'm sending u the response");
			System.out.println("control::SendResponse::run()::The response is : "+response);
			pl.debug("control::SendResponse::run()::The response is : "+response);
			pl.warn("control::SendResponse::run()::The response is : "+response);
			pl.fatal("control::SendResponse::run()::The response is : "+response);
			pl.error("control::SendResponse::run()::The response is : "+response);
			pl.trace("control::SendResponse::run()::The response is : "+response);
			
			outputResponse.flush();
			//outputResponse.println("The response is");
			//outputResponse.println(Username);
			outputResponse.flush();
			outputResponse.println(response);
			//out.flush();
			if(response.toLowerCase().contains("error"))
			{
				SmsBuffer sms = new SmsBuffer();
				sms.addBufferLog(Username, response);
			}	
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}	
	}
}